/**
 * Created by Dendy on 2015/10/9.
 *
 * @author Dendy
 * @date 2016/3/31
 */
(function ($, W) {

    var ExcelExport = function () {
    };

    ExcelExport.prototype = {
        constructor: ExcelExport
    };
    // ~ 业务逻辑入口 ====================================================================================================

    ExcelExport.prototype.dateFormat = function(time, format){
        var t = new Date(time);
        var tf = function(i){return (i < 10 ? '0' : '') + i};
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
            switch(a){
                case 'yyyy':
                    return tf(t.getFullYear());
                    break;
                case 'MM':
                    return tf(t.getMonth() + 1);
                    break;
                case 'mm':
                    return tf(t.getMinutes());
                    break;
                case 'dd':
                    return tf(t.getDate());
                    break;
                case 'HH':
                    return tf(t.getHours());
                    break;
                case 'ss':
                    return tf(t.getSeconds());
                    break;
            }
        })
    }

    /**
     * 导出文件:读后台的数据
     */
    ExcelExport.prototype.export = function(fileName, dataSheets){
        console.log(JSON.stringify(dataSheets));
        var content = "[";
        for ( var i = 0; i < dataSheets.length; i++) {
            if (i > 0) {
                content += ",";
            }
            var jsonData = JSON.stringify(dataSheets[i].data);
            content += "{sheetname:'" + dataSheets[i].sheetname + "', data:"
            + jsonData + "}";
        }
        content += "]";
        _saveFileExcel(fileName, content);
    };

    function _saveFileExcel(filename, content){
        var myForm = document.createElement("form");
        myForm.method="post" ;
        myForm.action = app_path + "/public/common/exportExcel.jsp";
        var nameInput = document.createElement("input") ;
        nameInput.setAttribute("type", "hidden") ;
        nameInput.setAttribute("name", "fileName") ;
        nameInput.setAttribute("value", filename);
        myForm.appendChild(nameInput) ;
        var contentInput = document.createElement("input") ;
        contentInput.setAttribute("type", "hidden") ;
        contentInput.setAttribute("name", "fileContent") ;
        contentInput.setAttribute("value", content);
        myForm.appendChild(contentInput) ;
        document.body.appendChild(myForm) ;
        myForm.submit() ;
        document.body.removeChild(myForm) ;
    }

    W.ExcelExport = new ExcelExport();

})(window.jQuery, window);
